<script>
import { ArrowDown, Expand, Fold } from "@element-plus/icons-vue";
import { doGet } from "../http/httpRequest.js";
import { clearToken, msgConfirm, msgTip } from "../util/util.js";

export default {
  name: "MainView",
  components: { ArrowDown, Expand, Fold },
  data() {
    return {
      /* 控制菜单的展开与折叠，true:折叠，false:展开 */
      isCollapse: false,
      // 用户信息
      user: {},
      isRouterAlive: true,
      currentRouterPath: '',
      // 菜单权限
      menu: [],
      // 权限
      permission: [],
      breadcrumbItems: [] // 面包屑导航数据
    };
  },

  // 在父页面提供一些属性、函数...等等，那么在其他子页面就可以注入使用
  provide() {
    return {
      // 提供一个函数 (页面局部刷新函数)
      reload: () => {
        this.isRouterAlive = false;
        this.$nextTick(function () {
          this.isRouterAlive = true;
        });
      },

      // 提供一个属性
      phone: '13720202020',

      // 提供一个数组
      idArray: [1, 2, 3, 4, 5],

      // 提供一个对象
      user: { id: 10389, name: '张三', age: 18 }
    };
  },

  methods: {
    showMenu() {
      this.isCollapse = !this.isCollapse;
    },
    getLoginUser() {
      doGet("/system/user/loginUserInfo", {}).then(resp => {
        if (resp.data.code === 200) {
          /* 把响应回来的结果赋值给user */
          this.user = resp.data.data;
        }
      });
    },
    getPermission() {
      // 从sessionStorage中获取权限信息
      let permission = sessionStorage.getItem("permission");
      // 如果不为空，则解析出权限信息
      if (permission) {
        this.permission = JSON.parse(permission);
      } else {
        doGet("/system/user/getPermissions", {}).then(resp => {
          if (resp.data.code === 200) {
            this.permission = resp.data.data;
            sessionStorage.setItem("permission", JSON.stringify(resp.data.data));
          }
        });
      }
    },
    getMenu() {
      // 从sessionStorage中获取菜单权限信息
      let menu = sessionStorage.getItem("menu");
      // 如果不为空，则解析出菜单权限信息
      if (menu) {
        this.menu = JSON.parse(menu);
      } else {
        doGet("/system/user/getMenu", {}).then(resp => {
          if (resp.data.code === 200) {
            this.menu = resp.data.data;
            sessionStorage.setItem("menu", JSON.stringify(resp.data.data));
          }
        });
      }
    },

    logout() {
      doGet("/system/user/logout", {}).then(resp => {
        if (resp.data.code === 200) {
          // 退出成功，清除token
          clearToken();
          // 清除前端的权限与菜单记录
          window.sessionStorage.removeItem("permission");
          window.sessionStorage.removeItem("menu");

          msgTip(resp.data.message, 'success');
          window.location.href = "/";
        } else {
          msgConfirm("退出失败，是否要强制退出？").then(() => {
            clearToken();
            msgTip("强制退出成功", 'success');
            window.location.href = "/";
          }).catch(() => {
            msgTip("取消了退出", 'warning');
          });
        }
      }).catch(error => {
        console.log(error);
      }).finally(() => {
        // 最终一定会执行的操作
      });
    },
    /* 加载当前路由路径 */
    loadCurrentRouterPath() {
      let path = this.$route.path;
      let pathArr = path.split('/');
      if (pathArr.length >= 4) {
        this.currentRouterPath = "/" + pathArr[1] + "/" + pathArr[2] + "/" + pathArr[3];
      }
    },
    mainView() {
      this.$router.push("/main");
    },

    /* 实现菜单的选择跳转 */
    handleSelect(index) {
      this.$router.push(index);
    },

    // 动态生成面包屑导航
    generateBreadcrumb() {
      const route = this.$route;
      const matchedRoutes = route.matched;

      this.breadcrumbItems = matchedRoutes.map(route => ({
        path: route.path,
        name: route.meta.title || route.name
      }));
    }
  },
  mounted() {
    this.getLoginUser();
    this.loadCurrentRouterPath();
    this.getPermission();
    this.getMenu();
    this.generateBreadcrumb(); // 生成面包屑导航
  },
  watch: {
    $route(to, from) {
      this.generateBreadcrumb(); // 监听路由变化并重新生成面包屑导航
    }
  }
};
</script>

<template>
  <el-container>
    <!-- 左侧 -->
    <el-aside :width="isCollapse ? '64px' : '200px'">
      <div class="menu-title" @click="mainView" style="cursor: pointer">Bridge-X</div>
      <!--  菜单  -->
      <el-menu active-text-color="#6495ED"
               background-color="#eeeeee"
               class="el-menu--vertical"
               :default-active="currentRouterPath"
               style="border-right:solid 0"
               :unique-opened="true"
               :collapse="isCollapse"
               :collapse-transition="false"
               @select="handleSelect">

        <el-sub-menu :index="String(index + 1)" v-for="(mainMenu, index) in menu" :key="mainMenu.id">
          <template #title>
            <el-icon><component :is="mainMenu.icon"></component></el-icon>
            <span style="font-weight: 700">{{mainMenu.name}}</span>
          </template>
          <el-menu-item :index="subMenu.url" v-for="subMenu in mainMenu.permissionPOList" :key="subMenu.id">
            <el-icon><component :is="subMenu.icon"></component></el-icon>
            {{subMenu.name}}
          </el-menu-item>
        </el-sub-menu>

      </el-menu>

    </el-aside>
    <!-- 右侧 -->
    <el-container>
      <!--  头部  -->
      <el-header>
        <div v-if="isCollapse" class="menu-icon">
          <el-icon class="show" @click="showMenu" style="color:#213547">
            <Expand />
          </el-icon>
        </div>
        <div v-else class="menu-icon">
          <el-icon class="show" @click="showMenu" style="color:#213547">
            <Fold />
          </el-icon>
        </div>

        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/" class="breadcrumb">
          <el-breadcrumb-item v-for="(item, index) in breadcrumbItems" :key="index" :to="{ path: item.path }">
            {{ item.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>

        <el-dropdown :hide-on-click="false" class="user-dropdown">
        <span class="el-dropdown-link" style="color:#213547">
          {{user.name}}
          <el-icon class="el-icon--right"><arrow-down /></el-icon>
        </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>我的资料</el-dropdown-item>
              <el-dropdown-item>修改密码</el-dropdown-item>
              <el-dropdown-item divided @click="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>
      <!--  主体  -->
      <el-main>
        <router-view v-if="isRouterAlive"/>
      </el-main>
      <!--  底部  -->
      <el-footer>&copy;2020-2099 Bridge-X </el-footer>
    </el-container>
  </el-container>
</template>

<style scoped>
.el-aside {
  background-color: #f9f9f9;
  .menu-title {
    height: 35px;
    color: #213547;
    text-align: center;
    line-height: 35px;
  }
}

.el-container {
  height: calc(100vh);
  .el-header {
    display: flex;
    justify-content: space-between;
    background-color: #eeeeee;
    height: 35px;
    line-height: 35px;
    align-items: center; /* 确保内容垂直居中 */
    .menu-icon {
      order: 1; /* 确保菜单图标在最左边 */
    }
    .breadcrumb {
      order: 2; /* 确保面包屑导航在菜单图标之后 */
      flex:1;
      margin-left: 10px; /* 添加一些左侧外边距 */
    }
    .user-dropdown {
      order: 3; /* 确保用户下拉菜单在最右边 */
      line-height: 35px;
    }
  }
  .el-footer {
    height: 35px;
    line-height: 35px;
    text-align: center;
    background-color: #eeeeee;
  }
}

.el-breadcrumb {
  line-height: 35px;
}
</style>
